package com.miszczu.bo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.miszczu.dao.AccounttypesDao;
import com.miszczu.dao.UsersDao;
import com.miszczu.model.Accounttypes;
import com.miszczu.model.Classes;
import com.miszczu.model.Users;

@Service
public class UsersBoImpl implements UsersBo {

	@Autowired
	private UsersDao usersDao;
	
	@Autowired
	private AccounttypesDao accounttypesDao;
	
	public Long getNumberOfUsersForClass(String userType, Integer classId) {
		
		return usersDao.getNumberOfUsersForClass(userType, classId);
		
	}

	public List<Users> getUsersForsClass(String userType, Integer classId) {

		return usersDao.getUsersForsClass(userType, classId);
	}

	public void save(Users user, String userType) {
		
		Accounttypes accountType = accounttypesDao.getAccountType(userType);
		user.setAccounttypes(accountType);
		
		// TODO:
		// Hashowanie hasla + salt
		user.setSalt("12345");
		
		usersDao.save(user);
		
	}

	public void addUserToClass(Users user, Classes classes) {
		
		Set<Classes> classesSet = user.getClasseses();
		classesSet.add(classes);
		
		user.setClasseses(classesSet);
		
		usersDao.update(user);
		
	}

	public List<Users> getAllStudents() {

		return usersDao.getAllUsers(UsersDao.STUDENT);
	}

	public Users getOne(Integer id) {
		
		return usersDao.getOne(id);
	}

	public void update(Users user) {
		
		usersDao.update(user);
		
	}

	@Transactional
	public void delete(Integer id) {

		Users user = usersDao.getOne(id);
		usersDao.delete(user);
		
	}

	public List<Users> getAllTeachers() {

		return usersDao.getAllUsers(UsersDao.TEACHER);
		
	}

	public boolean isLoginTaken(String login) {
		
		if(usersDao.getOneByLogin(login) != null) {
			return true;
		}
		
		return false;
	}

	public Users getLoggedUser() {

		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		
		String login = auth.getName();
		Users user = usersDao.getOneByLogin(login);
		
		return user;
	}

}
